import { _decorator, Color, Component, EditBox, game, Node, Sprite, sys, tween, UITransform, Vec3, view } from 'cc';
import { aa } from '../frame/FrameCore';
import { ChatType, Clips, Key, ui } from '../frame/common/Enums';
import chatMgr from '../manager/ChatMgr';
import commonMgr from '../manager/CommonMgr';
import { ChatBoxView } from '../view/ChatBoxView';
import configs from '../Configs';
import speech from './SpeechCtrl';
import { QuickBoxCtrl } from './QuickBoxCtrl';
import oh from './OhCtrl';
import { DecoCtrl } from './DecoCtrl';
const { ccclass, property } = _decorator;
const normalCol = new Color(84, 80, 104, 70);
const epressCol = new Color(84, 80, 120, 130);
const showPos = new Vec3(0, 0, 0);
const hidePos = new Vec3(0, -1500, 0);
const scaled = new Vec3(1.2, 1.2, 1.2);
const nMic = new Color(235, 235, 252, 240);
const pMic = new Color(228, 226, 250, 234);
declare var window: any

@ccclass('ChatCtrl')
export class ChatCtrl extends Component {
    @property(EditBox) editBox: EditBox;
    @property(Sprite) editBg: Sprite;
    @property(Node) functions: Node;
    @property(Node) talkPanel: Node;
    @property(Node) root: Node;
    @property(Node) mic: Node;
    @property(Node) bigMic: Node;
    @property(QuickBoxCtrl) quickBox: QuickBoxCtrl;

    static ins: ChatCtrl = null
    _wechatBrower = false;
    _wechat = 0;
    private _hand: Node = null;
    private _chatBox: ChatBoxView;

    isWeixinBrowser() {
        // window.navigator.userAgent属性会返回浏览器的用户代理字符串，
        // 其中包含了描述浏览器特征的各种信息
        var ua = window.navigator.userAgent.toLowerCase();
        // 使用正则表达式检查是否包含'micromessenger'字符串
        return (/micromessenger/.test(ua)) ? true : false;
    }

    onEnable(): void {
        // director.on(aaEvent.functionNotice, this.functionNotice, this);
        // chatMgr.presetChats();
        const self = this;
        window.startMic = function (text) {
            self.startMicCB(text);
        }
        window.endMic = function (text) {
            self.endMicCB(text);
        }
        this.quickBox.callback = function (text) {
            self.createChat(configs.userName, text, 1)
            const mode = aa.global.chatMode;
            self.chat(mode, text);
        }

    }
    onDisable(): void {
        // director.off(aaEvent.functionNotice, this.functionNotice, this);
        this.clear();
    }
    functionNotice(index) {
        this.clearHand();
        const icon = this.functions.children[index].getChildByName("icon");
        tween(icon).repeat(4, tween(icon).to(0.5, { scale: scaled }).to(0.5, { scale: Vec3.ONE })).start();
        this.scheduleOnce(() => {
            this._hand = commonMgr.showHand(icon.worldPosition, 0.5, true);
            this.scheduleOnce(this.clearHand, 4)
        })

    }
    clearHand() {
        this.unschedule(this.clearHand)
        if (this._hand) aa.res.put(this._hand)
        this._hand = null;

    }
    start() {
        ChatCtrl.ins = this;
        this._wechatBrower = this.isWeixinBrowser();
        this.newChatBox().createChat(configs.botName, `欢迎！我是智能助理${configs.botName},欢迎使用！`);
        this.scheduleOnce(() => {
            const chatBox2 = this.newChatBox().onWait();
            this.scheduleOnce(() => {
                chatBox2 && chatBox2.createChat(configs.botName, `点击右上角拍照上传户型图试试`);
                // oh.speak("点击右上角拍照上传户型图试试");

            }, 1.2);
        }, 0.5);

        const newUser = aa.data.get(Key.NewUser);
        aa.ui.prompt({
            tittle: "使用说明",
            content: configs.toast,
            confirmCB: (() => {
                // aa.data.addCurrency(Key.Cash, 100);
            })
        })
        // const canSpeech = speech.init();
        // this.mic.active = canSpeech;
        if (sys.os == sys.OS.OPENHARMONY || sys.browserType == sys.BrowserType.CHROME) {
            if (sys.browserType == sys.BrowserType.CHROME) {
                speech.init();
            }
            // this.mic.on(Node.EventType.TOUCH_START,this.startMic,this);
            this.bigMic.on(Node.EventType.TOUCH_START, this.startMic, this);
            this.bigMic.on(Node.EventType.TOUCH_END, this.endMic, this);

            // this.mic.on(Node.EventType.TOUCH_END,this.endMic,this);
        } else {
            // this.mic.active = false;
            this.bigMic.active = false;

        }

        if (newUser) {

            aa.data.set(Key.NewUser, false);
        }
    }
    clear() {
        this._sat = 0;
        chatMgr.clearCache();
        aa.utils.cleanScene(this.talkPanel);
    }
    onHide() {
        tween(this.root).to(0.2, { position: hidePos }).start();

    }
    onShow() {
        tween(this.root).to(0.2, { position: showPos }).start();
    }
    showAllFun() {
        // this.functions.children.forEach((c) => {
        //     c.active = true;
        // })
    }
    hideStory() {
        this.functions.children[1].active = false;
    }
    hideGame() {
        this.functions.children[2].active = false;
    }
    hideQuiz() {
        this.functions.children[3].active = false;
    }
    hideGift() {
        this.functions.children[0].active = false;
    }

    showStory() {
        aa.sound.play(Clips.btn);
        this.clearHand();
        aa.ui.get(ui.StorySelectView);
        this.onHide();
    }
    _startedMic = false
    startMic() {
        aa.sound.stopBgm();
        if (sys.os == sys.OS.OPENHARMONY) {
            oh.ohASR(true);
        } else {
            speech.onStartCallback = this.startMicCB.bind(this);
            speech.onEndCallback = this.endMicCB.bind(this);
            speech.startRecord();
        }

        // this.mic.getChildByName("icon").getComponent(Sprite).color = pMic
        this.bigMic.getChildByName("icon").getComponent(Sprite).color = pMic
        this.bigMic.getChildByName("eff").active = true;

        return;
        if (!this._startedMic) {
            if (!speech.isListening) {
                speech.onStartCallback = this.startMicCB.bind(this);
                speech.onEndCallback = this.endMicCB.bind(this);
                speech.startRecord();
            }
            this.mic.getChildByName("icon").getComponent(Sprite).color = new Color(140, 120, 255, 255)
            this._startedMic = !this._startedMic;

        } else {
            this._startedMic = !this._startedMic;
            this.mic.getChildByName("icon").getComponent(Sprite).color = new Color(248, 230, 230, 230)
            if (speech.isListening) {
                this.endMic();
                return;
            }
        }

    }
    endMic() {
        aa.sound.resumeBgm();
        if (sys.os == sys.OS.OPENHARMONY) {
            oh.ohASR(false);
        } else {
            speech.endRecord();
            speech.onStartCallback = null;
            // speech.onEndCallback = null;
        }
        this.bigMic.getChildByName("icon").getComponent(Sprite).color = nMic
        this.bigMic.getChildByName("eff").active = false;
        return;
        speech.endRecord();
        speech.onStartCallback = null;
        speech.onEndCallback = null;
        if (this._chatBox) {
            aa.res.put(this._chatBox.node)
        }
    }
    startMicCB(text: string) {
        // console.log("cocos info start mic cb"+text)
        if (!this._chatBox) {
            this._chatBox = this.newChatBox().onWait(configs.userName, 1);
        } else {
            if (text.length > 0) {
                this._chatBox.updateContent(text);
            }
        }
    }


    endMicCB(text: string) {
        console.log("cocos info end mic cb" + text)

        if (text.length <= 1) {
            if (this._chatBox) {
                aa.res.put(this._chatBox.node);
            }
        } else {
            aa.sound.play(Clips.btn);
            this._chatBox.updateContent(text);
            const mode = aa.global.chatMode;
            this.chat(mode, text);
            this._chatBox = null;
        }
    }


    onEditBegin() {
        aa.sound.play(Clips.btn);
        // game.frameRate = 30;

        // aa.global.playerCtrl.play(anmClip.talk)
        const width = view.getVisibleSize().width * 0.5;
        const trans = this.editBox.getComponent(UITransform);
        trans.width = width;
        // this.mic.scale = Vec3.ZERO;
        this.editBg.node.getComponent(UITransform).width = width + 20;
        // this.functions.setPosition(2000, 0, 0);
        this.editBg.color = epressCol;
        const isMobileBrower = sys.isMobile && sys.isBrowser;
        if (!isMobileBrower) return
        // this.node.getComponent(Widget).bottom = 0;
        const cam = aa.global.orbitCam;

        // cam.radius = 4.3;
        // cam.resetPosition();
    }

    onEditEnd() {
        console.log("onEnd")
        // game.frameRate = 60;

        // aa.global.playerCtrl.play(anmClip.idle)
        const trans = this.editBox.getComponent(UITransform);
        this.editBg.node.getComponent(UITransform).width = 400;
        // this.mic.scale = Vec3.ONE;
        // this.functions.setPosition(96, 0, 0);
        this.editBg.color = normalCol;
        trans.width = 400;
        const isMobileBrower = sys.isMobile && sys.isBrowser;
        if (!isMobileBrower) return
        // this.node.getComponent(Widget).bottom = 20;
        const cam = aa.global.orbitCam;
        // cam.height = 2;
        // cam.radius = 4.6;
        // cam.resetPosition();
    }

    onTextChange() {
        const string = this.editBox.string;
        if (string.length >= 40) {
            aa.ui.toast("已达到最大字数40");
        }
    }
    onEditReturn() {
        // if (this._isRun) {
        //     aa.ui.toast("主播正在回复,请稍后再试");
        //     return;
        // }
        console.log("onReturn")
        this._result = this.editBox.string;
        // if (aa.global.isTyping) 
        if (this._result.length <= 1) {
            aa.ui.toast("内容过短～")
            this.onEditEnd()
            return;
        }
        this.scheduleOnce(() => {
            this.editBox.string = "";
        })
        this.createChat(configs.userName, this._result, 1)
        const mode = aa.global.chatMode;
        this.chat(mode);
        this.onEditEnd()
    }

    createChat(name: string, content: string, index = 0) {
        this.newChatBox().createChat(name, content, index);
    }
    newChatBox(onWait = false) {
        let chatBoxNode = aa.res.get("ChatBox",);
        this.talkPanel.insertChild(chatBoxNode, 0);
        let chatBox = chatBoxNode.getComponent(ChatBoxView);
        const chats = this.talkPanel.children;

        this.scheduleOnce(() => {
            const height = this.talkPanel.getComponent(UITransform).height;
            if (height >= 320 || chats.length >= 4) {
                const first = chats.pop();
                aa.res.put(first);
            }
        })
        if (onWait) {
            chatBox.onWait();
        }
        return chatBox;
    }

    private _result: string = null;
    private _isRun = false
    private _sat = 0;
    // 新增顺序生成方法
    async generateImagesSequentially(items) {
        const length = items.length;
        if (length > 1) {
            for (let i = 0; i < items.length; i++) {
                const prompt = items[i];
                console.log(`正在生成第${i + 1}/${items.length}个家具图片` + prompt);
                // 先创建UI元素
                DecoCtrl.ins.generateFromPrompt(prompt, i);
                // 添加延迟避免过快请求
                if (i < items.length - 1) {
                    await new Promise(resolve => setTimeout(resolve, 450)); // 延迟500ms
                }
            }
        } else {
            DecoCtrl.ins.generateFromPrompt(items[0]);
        }

    }


    async chat(type: ChatType, result = this._result) {
        if (!result || aa.global.isTyping) return;
        const replayName = configs.botName;
        const index = type <= 4 ? 0 : 3;
        const aiChat = this.newChatBox().onWait(replayName, index);
        let json = await chatMgr.requestChat(result, aiChat);
        if (json != null && json[0] != null) {
            if (json) {
                this.quickBox.updataBox();
                const response = json[0].trim();
                if (/(func家具:)/.test(response)) {
                    // carCtrl.ins.openBack();  
                    let items = []
                    // 提取数组内容的正则表达式
                    const arrayMatch = response.match(/\[(.*?)\]/);
                    if (arrayMatch) {
                        const arrayContent = arrayMatch[1];
                        // 分割并清理每个元素
                        items = arrayContent.split(',').map(item => {
                            // 移除引号和多余空格
                            return item.trim().replace(/^['"]|['"]$/g, '');
                        });
                        if (items.length > 0) {
                            DecoCtrl.ins.setPressed(1);
                            aiChat.createChat(replayName, "正在为您定制个性化家具", index);

                            this.scheduleOnce(() => {
                                this.generateImagesSequentially(items);
                            })

                        } else {
                            aiChat.createChat(replayName, response, index);

                        }
                    }

                }

                else {
                    oh.ohTTS(json[0]);

                }
            }

        } else {
            aiChat.createChat(replayName, "哎呀,的网络信号不太好呀>.<", index)
            if (sys.platform == sys.Platform.OPENHARMONY) {
                // oh.speak("哎呀,的网络信号不太好呀");
            }
        }
        return;
    }

    extractRGB(input: string): number[] {
        const regex = /(\d+),(\d+),(\d+)/;
        const matches = input.match(regex);

        if (matches) {
            const [_, r, g, b] = matches;
            return [parseInt(r), parseInt(g), parseInt(b)];
        }

        return [200, 240, 200];
    }


}

